﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Timetable.Base;
using Timetable.Site.Attributes;
using Timetable.Site.Models;

namespace Timetable.Site.Controllers
{
    public partial class ScheduleController
    {
        
        public ActionResult SignIn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SignIn(SignInModel model)
        {
            AuthenticateService.OnSuccess += AuthenticateService_OnSuccess;
            AuthenticateService.OnFail += AuthenticateService_OnFail;
            AuthenticateService.Authenticate(model.Login, model.Password);

            return View(model);
        }

        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index");
        }

        [ValidateActivation]
        public ActionResult SignUp()
        {
            return View();
        }

        [HttpPost]
        [ValidateActivation]
        public ActionResult SignUp(SignUpModel model)
        {
            RegistrationService.OnFail += new EventHandler(RegistrationService_OnFail);
            RegistrationService.OnSuccess += new EventHandler(RegistrationService_OnSuccess);
            RegistrationService.Registration(model.User);

            return View("SignUpSuccess");
        }

        #region Private methods

        void RegistrationService_OnSuccess(object sender, EventArgs e)
        {
            Response.Redirect(Request["ReturnUrl"]);
        }

        void RegistrationService_OnFail(object sender, EventArgs e)
        {
            ModelState.AddModelError("Error", (sender as Exception).Message);
        }

        void AuthenticateService_OnFail(object sender, EventArgs e)
        {
            ModelState.AddModelError("Error", @Resources.Message.AuthorizeFailed);
        }

        void AuthenticateService_OnSuccess(object sender, Base.AuthenticateEventArgs e)
        {
            FormsAuthentication.Initialize();
            var ticket = new FormsAuthenticationTicket(e.Ticket.User.Login, true, (int)e.Ticket.ExpiryPeriod.TotalMinutes);

            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)));
            Response.Redirect(Request["ReturnUrl"]);
        }

        #endregion

    }
}
